/*
 * Copyright (c) 2020-2022 Jinsp-tech. All rights reserved.
 */

package com.jinsp.networklibrary.command;

import android.os.Handler;
import android.os.Looper;
import android.util.SparseArray;

import java.util.ServiceLoader;

/**
 * Created by luoshuai on 1/15/22
 * <p>
 * 命令管理
 */
public class CommandManager {

    private static volatile CommandManager INSTANCE;
    private SparseArray<ITCPCommand<?, ?>> mTCPCommandArray;
    private Handler mMainHandler;

    private CommandManager() {
    }

    public void init() {
        if (mTCPCommandArray == null) {
            mMainHandler = new Handler(Looper.getMainLooper());
            mTCPCommandArray = new SparseArray<>(20);
        }
        //获取所有命令
        ServiceLoader<ITCPCommand> serviceLoader = ServiceLoader.load(ITCPCommand.class);
        if (serviceLoader != null) {
            for (ITCPCommand<?, ?> handleTCPReceiveDataCommand : serviceLoader) {
                mTCPCommandArray.put(handleTCPReceiveDataCommand.getCommandNumber(), handleTCPReceiveDataCommand);
            }
        }
    }

    public static CommandManager getInstance() {
        if (INSTANCE == null) {
            synchronized (CommandManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new CommandManager();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 根据命令号获取对应命令
     *
     * @param commandNumber 命令号
     * @return 该命令号对应的命令
     */
    public ITCPCommand<?, ?> getCommand(int commandNumber) {
        return mTCPCommandArray.get(commandNumber);
    }

    /**
     * 获取所有注册的命令
     *
     * @return 所有通过SPI注册的命令
     */
    public SparseArray<ITCPCommand<?, ?>> getTCPCommandArray() {
        return mTCPCommandArray;
    }

    /**
     * 分发具体命令处理，判断是否切换主线程
     *
     * @param tcpCommandData 具体命令数据
     */
    public void dispatchCommand(TCPCommandData tcpCommandData) {
        if (tcpCommandData != null) {
            ITCPCommand<?, ?> tcpCommand = mTCPCommandArray.get(tcpCommandData.getCommandNumber());
            if (tcpCommand != null) {
                if (tcpCommand.isMainThread()) {
                    //切换主线程执行
                    mMainHandler.post(() -> tcpCommand.handleCommand(tcpCommandData.getState(), tcpCommandData.getData()));
                } else {
                    tcpCommand.handleCommand(tcpCommandData.getState(), tcpCommandData.getData());
                }
            }
        }
    }

    /**
     * 释放命令
     */
    public void release() {
        if (mMainHandler != null) {
            mMainHandler.removeCallbacksAndMessages(null);
            mMainHandler = null;
        }
        if (mTCPCommandArray != null) {
            mTCPCommandArray.clear();
            mTCPCommandArray = null;
        }
    }
}
